package com.taobao.auth.controller;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.taobao.ucenter.model.po.UserAuth;
import com.taobao.ucenter.service.WxAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Slf4j
@Controller
public class WxLoginController {

    @Lazy
    @Autowired
    WxAuthService wxAuthService;
    @Autowired
    RedisTemplate redisTemplate;


    /**
     * 获取微信登录二维码
     */
    @GetMapping("/getWeChatQRCode")
    @ResponseBody
    public String getWeChatQRCode() {

        String weChatQRCode = wxAuthService.getWeChatQRCode();

        return weChatQRCode;
    }

    @RequestMapping("/wxLogin")
    public String wxLogin(String code, String state) throws IOException {
        log.debug("微信扫码回调,code:{},state:{}", code, state);
        //远程调用微信请令牌，拿到令牌查询用户信息，将用户信息写入本项目数据库
        UserAuth userAuth = wxAuthService.wxAuth(code);

        if (userAuth == null) {
            return "redirect:http://www.baidu.com/";
        }
        String username = userAuth.getUsername();

        // 把username写入redis
        redisTemplate.opsForValue().set("username",username,5, TimeUnit.SECONDS);


//        return "redirect:http://10.102.2.86:8080/?username=" + username + "&authType=wx";
        return "redirect:http://www.baidu.com/";
    }

    /**
     * 获取username
     */
    @GetMapping("/getUsername")
    @ResponseBody
    public String getUsername() {
        String username = (String) redisTemplate.opsForValue().get("username");
        if (StringUtils.isEmpty(username)) {
            redisTemplate.delete("username");
        }
        return username;
    }
}
